package sources;

import net.rim.device.api.util.IntVector;
import pools.BasicMixingPool;
import pools.ConcatPool;
import pools.Pool;

public abstract class RandomSource {

	public abstract String getSourceName();

	private Pool[] pools = getPools();
	private IntVector rawData = new IntVector();
	
	public final void beginGenerating(long stopTime){
		openResources();
		while(System.currentTimeMillis() < stopTime){
			generateNext();
		}
		closeResources();
	}
	
	private Pool[] getPools() {
		return new Pool[] {
			new ConcatPool(),
			new BasicMixingPool()
		};
	}

	protected abstract void generateNext();
	
	protected void addToPools(int nextInt){
		for(int i = 0; i < pools.length; i++){
			pools[i].add(nextInt);
		}
	}

	public void clearBuffers() {
		pools = getPools();
		rawData = new IntVector();
	}

	public SaveableData[] getSaveableData() {
		SaveableData[] data = new SaveableData[pools.length];
		for(int i = 0; i < data.length; i++){
			data[i] = new SaveableData(getSourceName(), pools[i].getPoolName(), pools[i].getBuffer(), rawData.toArray());
		}
		return data;
	}
	
	protected abstract void openResources();
	protected abstract void closeResources();
	
	protected void addRawData(int i){
		rawData.addElement(i);
	}
	
}
